package com.mianyang.zhangsan.plugin.quartz;

import com.mianyang.zhangsan.common.util.ApplicationContextHelper;
import com.mianyang.zhangsan.common.util.JsonUtils;
import com.mianyang.zhangsan.model.entity.SecTask;
import com.mianyang.zhangsan.model.entity.SecTaskLog;
import com.mianyang.zhangsan.plugin.quartz.contant.QuartzConstant;
import com.mianyang.zhangsan.service.SecTaskLogService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.util.Assert;


/**
 * @author jiangjr
 * @date 2022-11-19
 */
@Slf4j
public abstract class AbstractJob implements Job {

    @Override
    public void execute(JobExecutionContext context){
        before();
        SecTask task = null;
        try {
            task = JsonUtils.toBean(context.getMergedJobDataMap().get(QuartzConstant.QUARTZ_TASK_KEY).toString(), SecTask.class);
            doExecute(context, task);
        } catch (Exception e) {
            log.error("定时任务执行异常-{}", e.getMessage());
            after(task, e);
        }
        after(task, null);
    }

    protected void before() {
    }

    protected void after(SecTask task, Exception e) {
        Assert.notNull(task, "执行任务不能为空");
        // 记录定时任务日志
        SecTaskLog taskLog = SecTaskLog.builder()
                .taskName(task.getTaskName())
                .taskId(task.getTaskId())
                .taskGroup(task.getTaskGroup())
                .taskParam(task.getTaskParam())
                .taskTime(task.getTaskTime())
                .taskType(task.getTaskType())
                .accountId(task.getAccountId())
                .accountName(task.getAccountName()).build();
        if (e != null) {
            taskLog.setLogMessage("任务执行失败" + e.getMessage());
        }else {
            taskLog.setLogMessage("任务执行成功");
        }
        ApplicationContextHelper.getBean(SecTaskLogService.class).save(taskLog);
    }

    /**
     * 定时任务执行逻辑
     * @param context 上下文变量
     * @param task 任务
     */
    protected abstract void doExecute(JobExecutionContext context, SecTask task);
}
